package com.hly.basickotlin.base

import android.app.Activity
import android.graphics.Color

import android.os.Bundle
import android.support.annotation.LayoutRes
import android.support.constraint.ConstraintLayout
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import butterknife.ButterKnife
import butterknife.Unbinder

import com.githang.statusbar.StatusBarCompat
import com.hly.basickotlin.R
import com.hly.basickotlin.utils.HideKey
import com.hly.basickotlin.utils.Utils

/**
 * ~~~~~~文件描述:~~~~~~
 * ~~~~~~作者:huleiyang~~~~~~
 * ~~~~~~创建时间:2018/7/13~~~~~~
 * ~~~~~~更改时间:2018/7/13~~~~~~
 * ~~~~~~版本号:1~~~~~~
 *
 */

abstract class BaseFragment : Fragment() {
    protected lateinit var statusBar: View
    private var unbinder: Unbinder? = null
    var mActivity: Activity? = null
    lateinit var mView: View
    internal var isLoad = false
    internal var isInit = false


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mActivity = activity
        if (isCustomStatusBar()) {
            mView = inflater.inflate(R.layout.fragment_base, container, false)
            statusBar = mView.findViewById(R.id.status_bar)
            statusBar.layoutParams = ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, Utils.getStatusBarHeight(mActivity))
            val view = LayoutInflater.from(context).inflate(getLayoutId(), null)
            (mView.findViewById(R.id.base_fragment_parent) as FrameLayout).addView(view)
            customStatusBar()
        } else {
            mView = inflater.inflate(getLayoutId(), container, false)
        }


        HideKey.init(mActivity)
        unbinder = ButterKnife.bind(this, mView)
        initView()
        isInit = true
        isCanLoadData()
        return mView
    }


    protected fun isCustomStatusBar(): Boolean {
        return false
    }

    protected fun customStatusBar() {
        statusBar.setBackgroundColor(Color.WHITE)
        StatusBarCompat.setLightStatusBar(activity!!.window, true)
    }


    abstract fun getLayoutId(): Int

    abstract fun initView()

    /**
     * 视图是否已经对用户可见，系统的方法
     */
    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        isCanLoadData()
    }

    //懒加载
    private fun isCanLoadData() {
        if (!isInit) {
            return
        }
        if (userVisibleHint && !isLoad) {//如果可见的话，加载数据
            lazyLoad()
            isLoad = true
        } else {
            if (isLoad) {
                stopLoad()
            }
        }
    }

    //第一次加载的处理
    abstract fun lazyLoad()

    //页面停止加载的处理
    abstract fun stopLoad()


    override fun onDestroy() {
        super.onDestroy()
        isInit = false
        unbinder!!.unbind()

    }


}
